import { RouteType } from '.'
import routerId from './routerId'
import NotFoundPage from '@/404'
import App from '@/App'
import Permission from '@/components/permissions/Permission'
import ErrorPage from '@/ErrorPage'
// import ComponManagement from '@/pages/accessManagement/ComponManagement'
// import ResourceManangement from '@/pages/accessManagement/ResourceManangement'
// import Resource from '@/pages/accessManagement/ResourceManangement/Resource'
// import RoleManangement from '@/pages/accessManagement/RoleManangement'
// import UserManagement from '@/pages/accessManagement/UserManagement'
import BannedList from '@/pages/user/userManage/bannedList'
import UserList from '@/pages/user/userManage/userList'
import UserDetail from '@/pages/user/userManage/userList/userDetail'
import GroupList from '@/pages/group/groupManage/groupList'
import AddGroup from '@/pages/group/groupManage/groupList/addGroup'
import GroupMember from '@/pages/group/groupManage/groupList/groupMember'
import Home from '@/pages/Home'
import Login from '@/pages/Login'
import Test from '@/pages/Test'
import TestChild from '@/pages/Test/TestChild'
import MenuManage from '@/pages/setting/enterpriseManage/menuManage'
import MenuDetail from '@/pages/setting/enterpriseManage/menuManage/menuDetail'
import StaffManage from '@/pages/setting/enterpriseManage/staffManage'
import StaffDetail from '@/pages/setting/enterpriseManage/staffManage/staffDetail'
import RoleManange from '@/pages/setting/enterpriseManage/roleManage'
import IpManange from '@/pages/setting/ipManage'
import LogManage from '@/pages/setting/logManage'
import AppVersionManage from '@/pages/setting/appVersionManage'
import GroupMessage from '@/pages/message/messageManage/groupMessage'
import UserMessage from '@/pages/message/messageManage/userMessage'
import KeyManage from '@/pages/setting/keyManage'
import {
  HomeOutlined,
  LockOutlined,
  UserOutlined,
  UsergroupAddOutlined,
  SettingOutlined,
  MessageOutlined
} from '@ant-design/icons'
import { Navigate } from 'react-router-dom'
// import { generateRoutes } from "./routeUtils"
import { getAvailableMenu } from '@/apis/accessManagement/menu'
import { getUserMenu } from '@/apis/accessManagement/menu'
import { message, Modal } from 'antd'
import { storeGlobalUser } from '@/store/globalUser'
// import * as Icons from "@ant-design/icons";

// const routersData = () => {
// const [menuData, setMenuData] = useState([]);
// 查询菜单
const setMenu = async () => {
  try {
    const response = await getAvailableMenu({})
    console.log(response,'response')
    if (response || response.data) {
      if (response?.errCode === 0) {
        // const menuTree = buildMenuTree(response.data.menuInfo); // 构建树
        // const routers = formatMenu(menuTree); // 格式化为 Ant Design Pro 菜单格式
        // return routers
        return response?.data?.menuInfo
      }
      message.error(`查询数据失败: ${response?.errMsg || '未知错误'}`)
    } else {
      message.error('响应数据格式错误')
    }
  } catch (error) {
    console.error('Error:', error)
  }
}

// 动态路由加载前确保roleId拿到
const waitForRoleId = (): Promise<number> => {
  return new Promise((resolve, reject) => {
    const interval = setInterval(() => {
      const roleId = storeGlobalUser.userInfo?.roleId
      if (roleId) {
        clearInterval(interval)
        resolve(roleId)
      }
    }, 100)
    // 超时处理
    setTimeout(() => {
      clearInterval(interval)
      reject(new Error('等待 roleId 超时'))
    }, 2000) // 2秒超时
  })
}

// 查询用户授权状态
const searchUserMenu = async () => {
  try {
    const roleId = await waitForRoleId()
    // const roleId = storage.get('roleId')
    const response = await getUserMenu({ roleId })
    if (response?.data?.menuIds && response.errCode === 0) {
      return response.data.menuIds || []
    }
    return []
  } catch (error) {
    console.error('Error in searchUserMenu:', error)
    return []
  }
}

// 更新查询授权后的菜单状态
const updateMenuStatus = async () => {
  try {
    const menuData = await setMenu() // 获取所有菜单数据
    const userMenuIds = await searchUserMenu() // 获取用户授权的菜单 ID 数组
    storeGlobalUser.setMenuInfo(menuData ?? [])
    storeGlobalUser.setUserAuths(userMenuIds ?? [])
    // storeGlobalUser.userInfo?
    if (menuData && userMenuIds) {
      const userID = await storeGlobalUser.userInfo?.userID
      if (userID !== 'imAdmin' && userMenuIds.length === 0) {
        Modal.warning({
          title: '提示',
          content: '当前账号未经过任何授权，请得到授权后再登陆！',
          okText: '确定',
          okCancel: false,
          onOk() {
            window.location.href = '/login'
          }
        })
        return
      }
      const updatedMenu = menuData.map((menuItem: any) => {
        // 如果 menuId 存在于 userMenuIds，则设置 status 为 1，否则为 2
        if (userMenuIds.includes(menuItem.menuId)) {
          return { ...menuItem, status: 1 }
        }
        return { ...menuItem, status: 2 }
      })
      const menuTree = buildMenuTree(userMenuIds.length > 0 ? updatedMenu : menuData) // 构建树
      const routers = formatMenu(menuTree) // 格式化为 Ant Design Pro 菜单格式
      return routers
      // console.log('Updated Menu:', updatedMenu);
    }
    console.warn('No menu data or user menu IDs found to process.')
  } catch (error) {
    console.error('Error in updateMenuStatus:', error)
  }
}

// 定义路径与组件的映射关系
const componentMap: Record<string, React.ReactNode> = {
  [routerId.home]: <Home />,
  [routerId.userList]: <UserList />,
  [routerId.addUser]: <UserDetail />,
  [routerId.setUser]: <UserDetail />,
  [routerId.bannedList]: <BannedList />,
  [routerId.groupList]: <GroupList />,
  [routerId.addGroup]: <AddGroup />,
  [routerId.setGroup]: <AddGroup />,
  [routerId.groupMember]: <GroupMember />,
  [routerId.staffManage]: <StaffManage />,
  [routerId.addStaff]: <StaffDetail />,
  [routerId.editStaff]: <StaffDetail />,
  [routerId.appVersionManage]: <AppVersionManage />,
  [routerId.roleManage]: <RoleManange />,
  [routerId.menuManage]: <MenuManage />,
  [routerId.addMenu]: <MenuDetail />,
  [routerId.setMenu]: <MenuDetail />,
  [routerId.userMessage]: <UserMessage />,
  [routerId.ipManange]: <IpManange />,
  [routerId.logManage]: <LogManage/>
}
/**
 * 动态加载图标
 * @param iconName 图标名称
 */
const Icons: any = {
  HomeOutlined,
  UserOutlined,
  UsergroupAddOutlined,
  SettingOutlined,
  MessageOutlined
}
const getIcon = (iconName: any) => {
  if (!iconName) {
    return null
  }
  const Icon = Icons[iconName] // 动态获取图标组件
  if (!Icon) {
    console.warn(`Icon "${iconName}" not found.`)
    return null
  }
  return <Icon />
}

/**
 * 构建菜单树
 * @param menuData 接口返回的扁平菜单数据
 */
const buildMenuTree = (menuData: any) => {
  const menuMap = new Map()
  const tree: any[] = []
  // 构建一个菜单映射，并初始化每个节点的子节点为空数组
  menuData.forEach((item: any) => {
    menuMap.set(item.menuId, { ...item, children: [] })
  })
  // 递归构建树形结构
  const buildTree = (node: any) => {
    if (node.menuParentId && menuMap.has(node.menuParentId)) {
      // 如果有父节点，添加到父节点的 children 中
      const parentNode = menuMap.get(node.menuParentId)
      parentNode.children.push(node)
      // 如果当前节点的 status 为 1，则将父节点的 status 设置为 1
      if (node.status === 1) {
        parentNode.status = 1
      }
    } else {
      // 如果没有父节点，视为根节点，加入树的根部
      tree.push(node)
    }
    // 递归处理所有子节点
    menuData
      .filter((child: any) => child.menuParentId === node.menuId)
      .forEach((child: any) => buildTree(menuMap.get(child.menuId)))
  }
  // 构建树
  menuData.forEach((item: any) => {
    if (!item.menuParentId || !menuMap.has(item.menuParentId)) {
      buildTree(menuMap.get(item.menuId))
    }
  })
  // 删除所有子节点 `status` 都为 2 的父节点
  const removeParentWithAllChildrenStatus2 = (parentNode: any): any => {
    // 递归检查每个子节点
    parentNode.children = parentNode.children
      .map((child: any) => {
        if (child.children && child.children.length > 0) {
          return removeParentWithAllChildrenStatus2(child)
        }
        return child.status === 2 ? null : child // 如果子节点的 status 为 2，则标记为 null
      })
      .filter((child: any) => child !== null) // 过滤掉被标记为 null 的子节点

    // 如果父节点的所有子节点都被移除，检查是否需要删除父节点
    if (parentNode.children.length === 0 && parentNode.status === 2) {
      return null // 父节点的所有子节点被删除，且父节点的 status 为 2，则删除父节点
    }

    return parentNode // 否则保留父节点
  }

  // 从树根开始，删除符合条件的父节点
  return tree.map(removeParentWithAllChildrenStatus2).filter((node: any) => node !== null)
}

/**
 * 格式化菜单为 Ant Design Pro 格式
 * @param menuTree 菜单树
 */
const formatMenu = (menuTree: any) => {
  return menuTree.map((node: any) => {
    return {
      path: node.path,
      name: node.menuName,
      icon: getIcon(node.icon),
      element: componentMap[node.path], // 动态匹配组件
      hideInMenu:
        node.menuName === '新增用户' ||
        node.menuName === '编辑用户' ||
        node.menuName === '新增群组' ||
        node.menuName === '编辑群组' ||
        node.menuName === '群组成员' ||
        node.menuName === '新增员工' ||
        node.menuName === '编辑员工' ||
        node.menuName === '修改白名单ip' ||
        node.menuName === '删除白名单ip' ||
        node.menuName === '新增白名单ip' ||
        node.menuName === '新增菜单' ||
        node.menuName === 'App版本添加' ||
        node.menuName === 'App版本修改' ||
        node.menuName === 'App版本删除' ||
        node.menuName === '修改菜单' ||
        node.menuName === '重置密码' ||
        node.menuName === '解散群组' ||
        node.menuName === '全体禁言' ||
        node.menuName === '修改App版本信息' ||
        node.menuName === '禁用'
          ? true
          : false,
      children: node.children.length > 0 ? formatMenu(node.children) : []
    }
  })
}

export const routers1 = () => {
  return new Promise((resolve, reject) => {
    updateMenuStatus().then(fetchedRoutes => {
      resolve([
        {
          path: '/',
          element: <Navigate replace to="/home" />
        },
        {
          path: '/',
          /** 承载布局 */
          element: <App />,
          errorElement: <ErrorPage />,
          icon: <UserOutlined />,
          children: [
            ...fetchedRoutes
            // {
            //     path: '/setting/keyManage',
            //     name: '字典管理',
            //     element: <KeyManage />
            // }
          ]
        },
        {
          path: '/login',
          name: '登录',
          element: <Login />
        },
        { path: '*', element: <NotFoundPage /> }
      ])
    })
    // searchUserMenu()
    // setMenu()
    //     .then((fetchedRoutes) => {
    //         resolve([
    //             {
    //             path: "/",
    //             element: <Navigate replace to="/home" />,
    //             },
    //             {
    //             path: "/",
    //             /** 承载布局 */
    //             element: <App />,
    //             errorElement: <ErrorPage />,
    //             icon: <UserOutlined />,
    //             children: [
    //                 ...fetchedRoutes,
    //             ],
    //             },
    //             {
    //             path: "/login",
    //             name: "登录",
    //             element: <Login />,
    //             },
    //         ]);
    //     })
  })
}

export const routers = [
  {
    path: '/',
    /** 重定向 */
    element: <Navigate replace to={routerId.home} />
  },
  {
    path: '/',
    /** 承载布局 */
    element: <App />,
    errorElement: <ErrorPage />,
    icon: <UserOutlined />,
    children: [
      /** 布局下路由，页面路由在该children配置 */
      {
        path: '/home',
        name: '首页',
        icon: <HomeOutlined />,
        element: <Home />
      },
      {
        path: '/user',
        name: '用户',
        icon: <UserOutlined />,
        children: [
          // {
          //     path: '/user/userManage',
          //     name: '用户管理',
          //     children: [
          {
            path: '/user/userManage/userList',
            name: '用户列表',
            element: <UserList />
          },
          {
            path: '/user/userManage/addUser',
            name: '新增用户',
            element: <UserDetail />,
            hideInMenu: true
          },
          {
            path: '/user/userManage/setUser',
            name: '编辑用户',
            element: <UserDetail />,
            hideInMenu: true
          },
          {
            path: '/user/userManage/bannedList',
            name: '封禁列表',
            element: <BannedList />
          }
        ]
        //     }
        // ]
      },
      // {
      //     path: '/accessManagement',
      //     name: '权限管理',
      //     icon: <LockOutlined/>,
      //     permissionObj: true,
      //     children: [
      //         {
      //             path: '/accessManagement',
      //             /** 重定向 */
      //             element: <Navigate replace to="/accessManagement/userManagement"/>
      //         },
      //         {
      //             path: '/accessManagement/userManagement',
      //             name: '用户管理',
      //             permissionObj: true,
      //             element: <UserManagement/>
      //         },
      //         {
      //             path: '/accessManagement/roleManagement',
      //             name: '角色管理',
      //             permissionObj: true,
      //             element: <RoleManangement/>
      //         },
      //         {
      //             path: '/accessManagement/componentManagement',
      //             name: '组件管理',
      //             permissionObj: true,
      //             element: <ComponManagement/>
      //         },
      //         {
      //             path: '/accessManagement/resourceManagement',
      //             name: '资源管理',
      //             permissionObj: true,
      //             children: [
      //                 {
      //                     path: '/accessManagement/resourceManagement',
      //                     /** 重定向 */
      //                     element: (
      //                         <Navigate replace to="/accessManagement/resourceManagement/resourceCategory"/>
      //                     )
      //                 },
      //                 {
      //                     path: '/accessManagement/resourceManagement/resourceCategory',
      //                     name: '资源分类',
      //                     permissionObj: true,
      //                     element: <ResourceManangement/>,
      //                     hideInMenu: true
      //                 },
      //                 {
      //                     path: '/accessManagement/resourceManagement/resourceCategory/:resourceCategoryId/resource',
      //                     name: '资源列表',
      //                     permissionObj: true,
      //                     element: <Resource/>,
      //                     hideInMenu: true
      //                 }
      //             ]
      //         }
      //     ]
      // },
      {
        path: '/group',
        name: '群组',
        icon: <UsergroupAddOutlined />,
        children: [
          // {
          //     path: '/group/groupManage',
          //     name: '群组管理',
          //     children: [
          {
            path: '/group/groupManage/groupList',
            name: '群组列表',
            element: <GroupList />
          },
          // {
          //   path: '/group/groupManage/addGroup',
          //   name: '新增群组',
          //   element: <AddGroup />,
          //   hideInMenu: true
          // },
          {
            path: '/group/groupManage/setGroup',
            name: '编辑群组',
            element: <AddGroup />,
            hideInMenu: true
          },
          {
            path: '/group/groupManage/groupMember',
            name: '群组成员',
            element: <GroupMember />,
            hideInMenu: true
          }
          // 封禁列表
          // {
          //     path: '/user/userManage/bannedList',
          //     name: '封禁列表',
          //     element: <BannedList/>,
          // }
        ]
        // }
        // ]
      },
      {
        path: '/layoutNone',
        name: '布局隐藏',
        hideInMenu: true,
        hideLayout: true,
        element: <TestChild />
      },
      {
        path: '/setting',
        name: '设置',
        icon: <SettingOutlined />,
        children: [
          // {
          //     path: '/setting/enterpriseManage',
          //     name: '企业管理',
          //     children: [
          //         {
          //             path: '/setting/enterpriseManage/staffManage',
          //             name: '员工管理',
          //             element: <StaffManage />
          //         },
          //         {
          //             path: '/setting/enterpriseManage/staffManage/addStaff',
          //             name: '新增员工',
          //             element: <StaffDetail />,
          //             hideInMenu: true
          //         },
          //         {
          //             path: '/setting/enterpriseManage/staffManage/editStaff',
          //             name: '修改员工',
          //             element: <StaffDetail />,
          //             hideInMenu: true
          //         },
          //         {
          //             path: '/setting/enterpriseManage/menuManage',
          //             name: '菜单管理',
          //             element: <MenuManage />
          //         },
          //         {
          //             path: '/setting/enterpriseManage/roleManage',
          //             name: '角色管理',
          //             element: <RoleManange />
          //         }
          //     ]
          // },
          {
              path: routerId.logManage,
              name: '日志管理',
              element: <LogManage />
          },
          {
            path: '/setting/enterpriseManage/staffManage',
            name: '员工管理',
            element: <StaffManage />
          },
          {
            path: '/setting/enterpriseManage/staffManage/addStaff',
            name: '新增员工',
            element: <StaffDetail />,
            hideInMenu: true
          },
          {
            path: '/setting/enterpriseManage/staffManage/editStaff',
            name: '编辑员工',
            element: <StaffDetail />,
            hideInMenu: true
          },
          {
            path: '/setting/appVersionManage',
            name: 'App版本管理',
            element: <AppVersionManage />
          },
          {
            path: '/setting/enterpriseManage/roleManage',
            name: '角色管理',
            element: <RoleManange />
          },
          {
            path: '/setting/enterpriseManage/menuManage',
            name: '菜单管理',
            element: <MenuManage />
          },
          {
            path: '/setting/enterpriseManage/menuManage/addMenu',
            name: '新增菜单',
            element: <MenuDetail />,
            hideInMenu: true
          },
          {
            path: '/setting/enterpriseManage/menuManage/setMenu',
            name: '修改菜单',
            element: <MenuDetail />,
            hideInMenu: true
          },
          {
            path: routerId.ipManange,
            name: '白名单管理',
            element: <IpManange />,
            hideInMenu: true
          }
          // {
          //     path: '/setting/keyManage',
          //     name: '字典管理',
          //     element: <KeyManage />
          // }
        ]
      },
      {
        path: '/message',
        name: '消息',
        icon: <MessageOutlined />,
        children: [
          {
            path: '/message/messageManage/userMessage',
            name: '消息管理',
            element: <UserMessage />
          }
          // {
          //     path: '/message/messageManage',
          //     name: '消息管理',
          //     children: [
          //         {
          //             path: '/message/messageManage/groupMessage',
          //             name: '群组消息',
          //             element: <GroupMessage />
          //         },
          //         {
          //             path: '/message/messageManage/userMessage',
          //             name: '用户消息',
          //             element: <UserMessage />
          //         }
          //     ]
          // }
        ]
      }
    ]
  },
  {
    path: '/login',
    name: '登录',
    element: <Login />
  },
  { path: '*', element: <NotFoundPage /> }
] as RouteType[]
